import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../models/prompt_model.dart';

/// Prompt 卡片组件 - Prompt Card Component
/// 用于显示 Prompt 的基本信息，支持列表和网格两种布局模式
class PromptCard extends StatelessWidget {
  final PromptModel prompt;
  final VoidCallback? onTap;
  final VoidCallback? onEdit;
  final VoidCallback? onDuplicate;
  final VoidCallback? onDelete;
  final VoidCallback? onFavoriteToggle;
  final VoidCallback? onLongPress; // 添加 onLongPress - Add onLongPress
  final bool isListView;
  final bool isSelected;
  final bool isSelectionMode; // 添加选择模式标识 - Add selection mode flag
  final VoidCallback? onSelectionChanged;

  const PromptCard({
    super.key,
    required this.prompt,
    required this.onTap,
    this.onFavoriteToggle,
    this.onEdit,
    this.onDuplicate,
    this.onDelete,
    this.onLongPress, // 添加 onLongPress - Add onLongPress
    this.isListView = false,
    this.isSelected = false,
    this.isSelectionMode = false, // 添加选择模式参数 - Add selection mode parameter
    this.onSelectionChanged,
  });

  @override
  Widget build(BuildContext context) {
    return Card(
      elevation: isSelected ? 8 : 2,
      color: isSelected ? Colors.blue.shade50 : null,
      margin: EdgeInsets.only(bottom: isListView ? 8 : 0),
      child: InkWell(
        onTap: onTap,
        onLongPress: onLongPress, // 支持长按 - Support long press
        borderRadius: BorderRadius.circular(12),
        child: Container(
          padding: const EdgeInsets.all(16),
          child: isListView
              ? _buildListLayout(context)
              : _buildGridLayout(context),
        ),
      ),
    );
  }

  /// 构建列表布局 - Build List Layout
  Widget _buildListLayout(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 左侧图标 - Left Icon
        Container(
          width: 48,
          height: 48,
          decoration: BoxDecoration(
            color: _getFileTypeColor().withOpacity(0.1),
            borderRadius: BorderRadius.circular(8),
          ),
          child: Icon(
            _getFileTypeIcon(),
            color: _getFileTypeColor(),
            size: 24,
          ),
        ),

        const SizedBox(width: 16),

        // 中间内容 - Middle Content
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 标题 - Title
              Text(
                prompt.title,
                style: Theme.of(context).textTheme.titleMedium?.copyWith(
                      fontWeight: FontWeight.w600,
                    ),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),

              const SizedBox(height: 4),

              // 描述 - Description
              if (prompt.description.isNotEmpty)
                Text(
                  prompt.description,
                  style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                        color: Colors.grey[600],
                      ),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),

              const SizedBox(height: 8),

              // 标签 - Tags
              if (prompt.tags.isNotEmpty)
                Wrap(
                  spacing: 4,
                  runSpacing: 4,
                  children:
                      prompt.tags.take(3).map((tag) => _buildTag(tag)).toList(),
                ),

              const SizedBox(height: 8),

              // 底部信息 - Bottom Info
              Row(
                children: [
                  Icon(
                    Icons.access_time,
                    size: 14,
                    color: Colors.grey[500],
                  ),
                  const SizedBox(width: 4),
                  Text(
                    _formatDate(prompt.getUpdatedAt()),
                    style: Theme.of(context).textTheme.bodySmall?.copyWith(
                          color: Colors.grey[500],
                        ),
                  ),
                  const Spacer(),
                  if (prompt.fileFormat.isNotEmpty)
                    Container(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 6, vertical: 2),
                      decoration: BoxDecoration(
                        color: Colors.grey[200],
                        borderRadius: BorderRadius.circular(4),
                      ),
                      child: Text(
                        prompt.fileFormat.toUpperCase(),
                        style: Theme.of(context).textTheme.bodySmall?.copyWith(
                              fontSize: 10,
                              fontWeight: FontWeight.w500,
                            ),
                      ),
                    ),
                ],
              ),
            ],
          ),
        ),

        // 右侧操作按钮 - Right Action Buttons
        if (!isSelected)
          PopupMenuButton<String>(
            onSelected: _handleMenuAction,
            itemBuilder: (context) => [
              const PopupMenuItem(
                value: 'edit',
                child: ListTile(
                  leading: Icon(Icons.edit, size: 20),
                  title: Text('编辑'),
                  contentPadding: EdgeInsets.zero,
                ),
              ),
              const PopupMenuItem(
                value: 'duplicate',
                child: ListTile(
                  leading: Icon(Icons.copy, size: 20),
                  title: Text('复制'),
                  contentPadding: EdgeInsets.zero,
                ),
              ),
              const PopupMenuItem(
                value: 'delete',
                child: ListTile(
                  leading: Icon(Icons.delete, size: 20, color: Colors.red),
                  title: Text('删除', style: TextStyle(color: Colors.red)),
                  contentPadding: EdgeInsets.zero,
                ),
              ),
            ],
            child: const Icon(Icons.more_vert, color: Colors.grey),
          ),
      ],
    );
  }

  /// 构建网格布局 - Build Grid Layout
  Widget _buildGridLayout(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        // 顶部：图标和操作按钮 - Top: Icon and Action Button
        Row(
          children: [
            Container(
              width: 40,
              height: 40,
              decoration: BoxDecoration(
                color: _getFileTypeColor().withOpacity(0.1),
                borderRadius: BorderRadius.circular(8),
              ),
              child: Icon(
                _getFileTypeIcon(),
                color: _getFileTypeColor(),
                size: 20,
              ),
            ),
            const Spacer(),
            if (!isSelected)
              PopupMenuButton<String>(
                onSelected: _handleMenuAction,
                itemBuilder: (context) => [
                  const PopupMenuItem(
                    value: 'edit',
                    child: ListTile(
                      leading: Icon(Icons.edit, size: 20),
                      title: Text('编辑'),
                      contentPadding: EdgeInsets.zero,
                    ),
                  ),
                  const PopupMenuItem(
                    value: 'duplicate',
                    child: ListTile(
                      leading: Icon(Icons.copy, size: 20),
                      title: Text('复制'),
                      contentPadding: EdgeInsets.zero,
                    ),
                  ),
                  const PopupMenuItem(
                    value: 'delete',
                    child: ListTile(
                      leading: Icon(Icons.delete, size: 20, color: Colors.red),
                      title: Text('删除', style: TextStyle(color: Colors.red)),
                      contentPadding: EdgeInsets.zero,
                    ),
                  ),
                ],
                child:
                    const Icon(Icons.more_vert, color: Colors.grey, size: 20),
              ),
          ],
        ),

        const SizedBox(height: 12),

        // 标题 - Title
        Text(
          prompt.title,
          style: Theme.of(context).textTheme.titleSmall?.copyWith(
                fontWeight: FontWeight.w600,
              ),
          maxLines: 2,
          overflow: TextOverflow.ellipsis,
        ),

        const SizedBox(height: 8),

        // 内容预览 - Content Preview
        Text(
          prompt.getContentPreview(),
          style: Theme.of(context).textTheme.bodySmall?.copyWith(
                color: Colors.grey[600],
              ),
          maxLines: 3,
          overflow: TextOverflow.ellipsis,
        ),

        const SizedBox(height: 12),

        // 标签 - Tags
        if (prompt.tags.isNotEmpty)
          Wrap(
            spacing: 4,
            runSpacing: 4,
            children: prompt.tags
                .take(2)
                .map((tag) => _buildTag(tag, isSmall: true))
                .toList(),
          ),

        const SizedBox(height: 12),

        // 底部信息 - Bottom Info
        Row(
          children: [
            Icon(
              Icons.access_time,
              size: 12,
              color: Colors.grey[500],
            ),
            const SizedBox(width: 4),
            Expanded(
              child: Text(
                _formatDate(prompt.getUpdatedAt()),
                style: Theme.of(context).textTheme.bodySmall?.copyWith(
                      color: Colors.grey[500],
                      fontSize: 11,
                    ),
              ),
            ),
            if (prompt.fileFormat.isNotEmpty)
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2),
                decoration: BoxDecoration(
                  color: Colors.grey[200],
                  borderRadius: BorderRadius.circular(3),
                ),
                child: Text(
                  prompt.fileFormat.toUpperCase(),
                  style: Theme.of(context).textTheme.bodySmall?.copyWith(
                        fontSize: 9,
                        fontWeight: FontWeight.w500,
                      ),
                ),
              ),
          ],
        ),
      ],
    );
  }

  /// 构建标签 - Build Tag
  Widget _buildTag(String tag, {bool isSmall = false}) {
    return Container(
      padding: EdgeInsets.symmetric(
        horizontal: isSmall ? 6 : 8,
        vertical: isSmall ? 2 : 4,
      ),
      decoration: BoxDecoration(
        color: Colors.blue.shade50,
        borderRadius: BorderRadius.circular(isSmall ? 8 : 12),
        border: Border.all(color: Colors.blue.shade200),
      ),
      child: Text(
        tag,
        style: TextStyle(
          color: Colors.blue.shade700,
          fontSize: isSmall ? 10 : 12,
          fontWeight: FontWeight.w500,
        ),
      ),
    );
  }

  /// 获取文件类型图标 - Get File Type Icon
  IconData _getFileTypeIcon() {
    switch (prompt.fileFormat.toLowerCase()) {
      case 'md':
      case 'markdown':
        return Icons.description;
      case 'txt':
        return Icons.text_snippet;
      case 'doc':
      case 'docx':
        return Icons.article;
      case 'pdf':
        return Icons.picture_as_pdf;
      default:
        return Icons.insert_drive_file;
    }
  }

  /// 获取文件类型颜色 - Get File Type Color
  Color _getFileTypeColor() {
    switch (prompt.fileFormat.toLowerCase()) {
      case 'md':
      case 'markdown':
        return Colors.blue;
      case 'txt':
        return Colors.grey;
      case 'doc':
      case 'docx':
        return Colors.indigo;
      case 'pdf':
        return Colors.red;
      default:
        return Colors.orange;
    }
  }

  /// 格式化日期 - Format Date
  String _formatDate(DateTime date) {
    final now = DateTime.now();
    final difference = now.difference(date);

    if (difference.inDays == 0) {
      if (difference.inHours == 0) {
        if (difference.inMinutes == 0) {
          return '刚刚';
        }
        return '${difference.inMinutes}分钟前';
      }
      return '${difference.inHours}小时前';
    } else if (difference.inDays == 1) {
      return '昨天';
    } else if (difference.inDays < 7) {
      return '${difference.inDays}天前';
    } else {
      return DateFormat('MM/dd').format(date);
    }
  }

  /// 处理菜单操作 - Handle Menu Action
  void _handleMenuAction(String action) {
    switch (action) {
      case 'edit':
        onEdit?.call();
        break;
      case 'duplicate':
        onDuplicate?.call();
        break;
      case 'delete':
        onDelete?.call();
        break;
    }
  }
}